var dataSource = new Array();
//table的数据源
var table;   //table对象
dataSource = [];



//运营经理关联
function myFunction(){
    //销售经理

    var manager=$("#organization_name").val();
    var user_data = {
        "pageNum":1,

        "pageSize":20,

    }
    var succCallBack = function (data, status, response) {
        console.log(data)
        if(data.errorCode=="0"){
            var jsonObj =data.group;
            if(jsonObj==""){
                $("#tuan").html("<li>无数据</li> ");
            }else {
                console.log(jsonObj)

                var optionstring = "";
                for (var  i= 0; i < jsonObj.length; i++) {
                    optionstring += "<li onclick='relation("+ jsonObj[i].id+",\""+jsonObj[i].organization_name+"\")' data-align=\"" + jsonObj[i].id + "\" > " + jsonObj[i].organization_name + "</li>";
                }
                $("#tuan").html(optionstring);
                console.log(jsonObj)
            }
        }else{
            $("#tuan").html("<li>无数据</li> ");
        }
    }
    /*root.member.getGroup*/
    web.doAjax(root.member.getGroup,'post',user_data, succCallBack);

}
//取光标
$("#organization_name").focus(function () {
    $("#tuan").show()
});
$(document).bind("click",function(e){
    //id为menu的是菜单，id为open的是打开菜单的按钮
    if($(e.target).closest("#tuan").length == 0 && $(e.target).closest("#organization_name").length == 0){
        //点击id为menu之外且id不是不是open，则触发
        $("#tuan").hide()
    }
})
function relation(id,ce) {
    $("#organization_name").val(ce).text(id)
    $("#tuan").hide()
    console.log($("#organization_name").text())
}

function zhikong() {
    $('.inputss').val('');
    $('select').val('');
    $("#organization_name").text('')
}


function searchList() {
    $.ajax({
        /*root.member.custAccountList*/
        url: root.member.queryCustomerManager,
        cache: false,  //禁用缓存
        type: "POST",
        dataType:'json',
        contentType: "application/json",
        data: JSON.stringify({
            "pageNum":1,
            "pageSize":20,


            "loginAccout":$("#login_account").val(),

            "customerId": $("#customerId").val(),

            "mainCustomer":$("#mainCustomer").val(),
            "customerName":$("#customerName").val(),

            "status":$("#status").val(),
            "relationId":$("#relation").val(),

            "groupId":$("#organization_name").text(),
            "phoneNumber":$("#phoneNumber").val(),
            "user":$("#user").val(),
            "registerSource":$("#registerSource").val(),
            "createTimeBegin":$("#createTimeBegin").val(),
            "createTimeEnd":$("#createTimeEnd").val(),
            "mainCustomerCode":$('#CustormerCode').val()
        }),
        success: function (data) {
            console.log(data);
            // couponlist(data.result);
            couponlist(data.data, 0);
            $('.M-box3').pagination({
                pageCount: data.data.pageCount,
                jump: true,
                coping: true,
                prevContent: '上页',
                nextContent: '下页',
                callback: function (api) {
                    console.log(api)
                    $.ajax({
                        /*root.member.custAccountList*/
                        url:root.member.queryCustomerManager,
                        cache: false,  //禁用缓存
                        type: "POST",
                        dataType:'json',
                        contentType: "application/json",
                        data: JSON.stringify({
                            "pageNum":api.getCurrent(),
                            "pageSize":20,

                            "loginAccout":$("#login_account").val(),

                            "customerId": $("#customerId").val(),

                            "mainCustomer":$("#mainCustomer").val(),
                            "customerName":$("#customerName").val(),

                            "status":$("#status").val(),
                            "relationId":$("#relation").val(),
                            "groupId":$("#organization_name").text(),
                            "phoneNumber":$("#phoneNumber").val(),
                            "user":$("#user").val(),
                            "registerSource":$("#registerSource").val(),
                            "createTimeBegin":$("#createTimeBegin").val(),
                            "createTimeEnd":$("#createTimeEnd").val(),
                            "mainCustomerCode":$('#CustormerCode').val()

                        }),
                        success: function (result) {
                            console.log(result)
                            couponlist(result.data);
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            alert(XMLHttpRequest);
                        }
                    });
                }
            });

        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    });
}

// var j = 0;
function couponlist(data, index){
    // var j = 0;
    sessionStorage.setItem("authorizedUsers", JSON.stringify(data.data));
    dataSource.splice(0,dataSource.length);//清空数组

    if(data.data !=null && data.data != ''){
        var datashu =data.startRow+1;


    $.each(data.data, function (i, field) {
        var rowData = new Array();
        var datashus = datashu++
        rowData.push(field.member_id);
        rowData.push(field.login_account);
        rowData.push(field.customer_id);
        rowData.push(field.customer_name);
        rowData.push(field.organization_name);
        rowData.push(field.register_time_value);
        rowData.push(field.createUser);
        rowData.push(field.status);
        rowData.push(datashus);
        rowData.push(field.main_customer_name);
        rowData.push(field.account_relation_type);
        rowData.push(field.id);
        rowData.push(field.register_time);
        dataSource.push(rowData);
    });
    }
    initDataTable(dataSource);

    function initDataTable(dataSource) {

        var dttable = $('#datatable').dataTable(); // 初始化dataTable，清空上一个值
        dttable.fnClearTable(); //清空一下table
        dttable.fnDestroy(); //还原初始化了的datatable
        $("#datatable").DataTable({
            // "order": false,
            "autoWidth": false,
            "ordering": false,
            "searching": false,
            "paging": false,
            "retrieve": true,
            "destroy": true,
            "bAutoWidth": true,
            "bLengthChange": true,
            "aLengthMenu": false,
            "oLanguage": {
                "sLengthMenu": "每页显示 _MENU_ 条记录",
                "sZeroRecords": "抱歉， 没有找到",
                "sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
                "sInfoEmpty": "没有数据",
                "sInfoFiltered": "(从 _MAX_ 条数据中检索)",
                "oPaginate": {
                    "sFirst": "首页",
                    "sPrevious": "前一页",
                    "sNext": "后一页",
                    "sLast": "尾页"
                },
                "sZeroRecords": "没有检索到数据",
            },
            data: dataSource,
            columnDefs: [
                {
                    "visible": true,
                    "targets": 0
                },

                {
                    "render": function (data, type, row, meta) {
                        var val = row[8]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 0
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[1]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 1
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = '';
                        var date = row[12];
                        var split = date.split(" ");
                        val = split[0] + '<br/>' + split[1];
                        return val;
                    },
                    "targets": 2
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[9]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 3
                },
                {
                    "render": function (data, type, row, meta) {
                        var val =""
                        if (row[2] != null && row[2] != "") {
                            val = row[2]
                        }else {
                            val ="--"
                        }
                        return val;
                    },
                    "targets": 4
                },
                {
                    "render": function (data, type, row, meta) {
                        var val =""
                        if (row[3] != null && row[3] != "") {
                            val = row[3]
                        }else {
                            val ="--"
                        }
                        return val;
                    },
                    "targets": 5
                },
                {
                    "render": function (data, type, row, meta) {
                        var val =""
                        if (row[4] != null && row[4] != "") {
                            val = row[4]
                        }else {
                            val ="--"
                        }
                        return val;
                        return val;
                    },
                    "targets": 6
                },
                {
                    "render": function (data, type, row, meta) {
                        var val =""
                        if (row[10] != null && row[10] != "") {
                            val = row[10]
                        }else {
                            val ="--"
                        }
                        return val;
                    },
                    "targets": 7
                },

                {
                    "render": function (data, type, row, meta) {
                        var val = '';
                        if(row[7]==10){
                            val='开启'
                        }
                        else if(row[7]==20){
                            val='关闭'
                        }
                        return val;
                    },
                    "targets":8
                },

                {
                    "render": function (data, type, row, meta) {
                        var val='';
                        if(row[7]==10){
                            val = '<div class="action" id="action'+row[0]+'"><a class="powerButton 171" style="margin-right: 20px"><span class="list" id="'+row[0]+'" onclick="confirm('+row[0]+')">关闭</span></a>'+
                                '<a class="powerButton 172"><span class="list"  onclick="detail(\'详情信息\',\'contractCustomer_see.html\',\''+row[1]+'\',\''+row[2]+'\',\''+row[11]+'\',\''+row[0]+'\')">查看</span></a></div>';


                        }
                        else if(row[7]==20){
                            val = '<div class="action" id="action'+row[0]+'"><a class="powerButton 171" style="margin-right: 20px"><span class="list" id="'+row[0]+'" onclick="confirm2('+row[0]+')">开启</span></a>'+
                                '<a class="powerButton 172"><span class="list"  onclick="detail(\'详情信息\',\'contractCustomer_see.html\',\''+row[1]+'\',\''+row[2]+'\',\''+row[11]+'\',\''+row[0]+'\')">查看</span></a></div>';




                        }
                        return val;
                    },
                    "targets":9
                }


            ]
        });
//权限控制函数
        power()
    };
}
//关闭弹框
var index=0;
function confirm(id,val) {
    var curInd = layer.confirm('<span id="status" style="width:200px;height:100px;resize: none;" maxlength="200" >您确定要关闭此账号吗？</span>', {title:'提示',btn: ['确定', '取消']}, function(index){

        finish1(id,curInd,val)
        layer.close(curInd);
    },function(){
        layer.close(curInd);

    });
}
//第一个
function finish1(id,val){
    var target = document.getElementById(''+id+'');
    target.parentElement.parentElement.parentElement.previousElementSibling.innerHTML='关闭';
    console.log(target)

    var reason=$('#reason'+id+'').val();
    console.log(reason)
    if(reason!=''){
        $.ajax({
            contentType: "application/json;charset=UTF-8",
            /*root.member.updateMemberStatus*/
            url:root.member.updateMemberStatus,
            cache: false,  //禁用缓存
            type: "POST",
            dataType:'json',
            data: JSON.stringify({
                "memberId":id,
                "status":20,
                optUserId:JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.user_ID,
                optUserName:JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.name

            }),
            success: function (data) {
                console.log(data)

                target.onclick = null;
                target.setAttribute("onclick", 'confirm('+id+')')
                target.parentElement.parentElement.parentElement.previousElementSibling.innerHTML='关闭'
                searchList();

            },
            error: function () {
                $.Huimodalalert('失败！',2000);
            }
        })}
    else{
        $.Huimodalalert('处理结果不能为空！',2000);
    };
    layer.close(index);
}

//开启弹框
var index=0;
function confirm2(id,val) {
    var curInd = layer.confirm('<span id="status" style="width:200px;height:100px;resize: none;" maxlength="200" >您确定要开启此账号吗？</span>', {title:'提示',btn: ['确定', '取消']}, function(index){

        finish2(id,curInd,val)
        layer.close(curInd);
    },function(){
        layer.close(curInd);

    });
}
//第一个
function finish2(id,val){
    var target = document.getElementById(''+id+'');

    target.parentElement.parentElement.parentElement.previousElementSibling.innerHTML='开启';

    var reason=$('#reason'+id+'').val();
    if(reason!=''){
        $.ajax({
            contentType: "application/json;charset=UTF-8",
            /*root.member.updateMemberStatus*/
            url:root.member.updateMemberStatus,
            cache: false,  //禁用缓存
            type: "POST",
            dataType:'json',
            data: JSON.stringify({
                "memberId":id,
                "status":10,
                optUserId:JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.user_ID,
                optUserName:JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.name

            }),
            success: function (data) {

                target.onclick = null;
                target.setAttribute("onclick", 'confirm('+id+')')
                searchList();
            },
            error: function () {
                $.Huimodalalert('失败！',2000);
            }
        })}
    else{
        $.Huimodalalert('处理结果不能为空！',2000);
    };
    layer.close(index);
}

//查看详情
function detail(title,url,loginAccout,customerId,id,memberid) {
    sessionStorage.setItem("loginAccout",loginAccout);
    sessionStorage.setItem("customerId",customerId);
    sessionStorage.setItem("ids",id);
    sessionStorage.setItem("memberid",memberid)
    var index = layer.open({
        type: 2,
        title: title,
        content: url
    })
    layer.full(index);

   /* window.location.href="contractCustomer_see.html"*/
}

